import { fetchList, createItem, updateCount, deleteItem } from "@/api/cart.js";
const state = {
  items: []
};
const getters = {
  getItems: state => {
    return state.items;
  }
};
const mutations = {
  addItem: (state, item) => {
    state.items.push(item);
  },
  setItems: (state, items) => {
    state.items = items;
  }
};
const actions = {
  pushItem: ({ dispatch }, item) => {
    createItem(item).then(() => {
      dispatch("pullItems");
    });
  },
  setCount: ({ dispatch }, { id, count }) => {
    updateCount(id, count).then(() => {
      dispatch("pullItems");
    });
  },
  deleteItem: ({ dispatch }, { id }) => {
    deleteItem(id).then(() => {
      dispatch("pullItems");
    });
  },
  pullItems: ({ commit }) => {
    fetchList().then(res => {
      if (res.code === 1) {
        commit("setItems", res.data.items);
      }
    });
  }
};
export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
};
